package com.winit.commons.util;


import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ObjectToString {


    public static String getString(Object o) {
        if (o == null)
            return null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        StringBuffer sb = new StringBuffer();
        sb.append("(");
        Field[] farr = o.getClass().getDeclaredFields();
        for (Field field : farr) {
            try {
                field.setAccessible(true);
                sb.append(field.getName());
                sb.append("=");
                if (field.get(o) instanceof Date) {
                    // 日期的处理
                    sb.append(sdf.format(field.get(o)));
                } else {
                    sb.append(field.get(o));
                }
                sb.append("|");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        sb.append(")");
        return sb.toString();
    }

    public static String getUrlString(Object o) {
        if (o == null)
            return null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        StringBuffer sb = new StringBuffer();
        Field[] farr = o.getClass().getDeclaredFields();
        for (Field field : farr) {
            try {
                StringBuffer s = new StringBuffer();
                field.setAccessible(true);
                s.append(field.getName());
                s.append("=");
                if (field.get(o) instanceof Date) {
                    // 日期的处理
                    s.append(sdf.format(field.get(o)));
                } else {
                    s.append(field.get(o));
                }
                if (!s.toString().endsWith("null") && !s.toString().endsWith("=")) {
                    sb.append(s.toString()).append("&");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return sb.toString().substring(0, sb.toString().length() - 1);
    }

}
